<?php
namespace Reezy\OAuth;

use Reezy\OAuth\Contract\OAuthFactoryInterface;
use Reezy\OAuth\Contract\OAuthInterface;
use function class_exists;
use function ucfirst;

class OAuthFactory implements OAuthFactoryInterface
{
    private $drivers = [];

    /**
     *
     * @param string $name
     *
     * @return OAuthInterface
     */
    public function get(string $name): OAuthInterface
    {
        if (isset($this->drivers[$name])) {
            return $this->drivers[$name];
        }
        $config = \config("oauth.$name");
        if (empty($config)) {
            throw new OAuthException("OAuth [$name] not found.");
        }

        if (isset($config['driver'])) {
            $driver = $config['driver'];
        } else {
            $driver = __NAMESPACE__ . '\\Driver\\OAuth' . ucfirst($name);
        }
        if (!class_exists($driver)) {
            throw new OAuthException("OAuth [$name] driver [$driver] not exists.");
        }
        if (empty($config['client_id']) || empty($config['client_secret'])) {
            throw new OAuthException("OAuth [$name] driver [$driver] client_id and client_secret are required.");
        }
        return $this->drivers[$name] = new $driver($config);
    }
}
